<?php
/**
 * 用户管理
 */
namespace app\backend\modules\user\controllers;

use app\api\modules\v1\market\models\Header;
use app\backend\components\BaseController;
use app\models\HttpCurl;
use Yii;
use app\models\base\User;
use app\models\base\BankAccount;
use yii\data\Pagination;
use app\backend\modules\user\models\Appuser;
use yii\helpers\Json;
use app\models\base\Role;

class UserinfoController extends BaseController
{
    const SUC = 200;
    const ERR = 400;
    public function init()
    {
        parent::init();
        $this->data['js'] = [
            'global/plugins/layer/layer.js',
            'global/plugins/dist/viewer.min.js',
            'backend/user/user.js',
            'global/plugins/3rd/jquery-1.11.3.min.js',
            'global/plugins/js/config.js',
            'global/plugins/js/md5.js',
            'global/plugins/js/register.js',
        ];
        $this->data['css'] = [
            'global/plugins/dist/viewer.min.css',
        ];
	}

    public static function strToHex($string)//字符串转十六进制
    {
        $hex="";
        for($i=0;$i<strlen($string);$i++)
            $hex.=dechex(ord($string[$i]));
//        $hex=strtoupper($hex);
        return $hex;
    }
	//用户列表
    public function actionIndex()
    {
    	$model = User::find();
    	$pages = new Pagination([
    			'totalCount' => $model->count(),
    		]);
    	$this->data['pages'] = $pages;
    	$model->limit($pages->limit);
    	$model->offset($pages->offset);
    	$user = $model->all();
    	$this->data['user'] = $user;
        return $this->render('index',$this->data);
    }

    //用户详情
    public function actionDetail()
    {
        $request = Yii::$app->request;
        $user_id = $request->get('user_id');
        $user = User::find()->where(['user_id'=>$user_id])->asArray()->one();
        $this->data['user'] = $user;
        return $this->render('detail',$this->data);
    }

    //办理离职
    public function actionLeave()
    {
        $request = Yii::$app->request;
        $user_id = $request->get('user_id');
        $submit = Appuser::userleave($user_id);
        // echo '<pre>';var_dump($submit);echo '</pre>';exit;
        if($submit == 200){
            $time = date('Y-m-d H:i:s',time());
            return json_encode(['code'=>self::SUC,'msg'=>'办理离职成功','time'=>$time]);
        }else{
            return json_encode(['code'=>self::ERR,'msg'=>'办理离职失败']);
        }
    }

    //添加用户
    public function actionAdd()
    {
        $request = Yii::$app->request;
        $attributes = $request->post('User');
        if($attributes){
            // echo '<pre>';var_dump($attributes);echo '</pre>';exit;
            $db = Yii::$app->db;
            $transaction = $db->beginTransaction();
            try {
                $attributes['password'] = md5(md5($attributes['password']));
                $attributes['birthday'] = strtotime($attributes['birthday']);
                $attributes['create_time'] = time();
                $attributes['start_time'] = time();
                $model = new User;
                $model->attributes = $attributes;
                $model->save();
                $models = new BankAccount;
                $models->user_id = $model->user_id;
                $models->create_time = time();
                $models->start_time = time();
                $submit = $models->save()?200:500;
                $this->data['submit'] = $submit;
                $info = self::setToken($model -> phone,$model-> name);

                //添加用户token和accid
                if(!empty($info)){
                    $user = User::findOne($model -> user_id);
                    if(!empty($user)){
                        $user -> token = $info['token'];
                        $user -> accid = $info['accid'];
                        $user -> save();
                    }
                }

                $transaction->commit();
            } catch (Exception $e) {
                // var_dump($e->getMessage());
                // exit;
                $transaction->rollBack();
                throw $e;
            }
        }
        $this->data['action'] = 'add';
        //角色
        $role = Role::find()->where(['disabled'=>0])->all();
        $this->data['role'] = $role;
        return $this->render('add',$this->data);
    }

    //编辑用户
    public function actionUpdate()
    {
        $user_id = Yii::$app->request->get('user_id');
        $attributes = Yii::$app->request->post('User');
        if($attributes){
        // echo '<pre>';var_dump($attributes); echo '</pre>';exit;
            $attributes['password'] = md5(md5($attributes['password']));
            $attributes['birthday'] = strtotime($attributes['birthday']);
            $model = User::findOne($user_id);
            $model->attributes = $attributes;
            $submit = $model->save()?200:500;
            $this->data['submit'] = $submit;
            // $this->refresh('&ref_sub='.$submit);
        }
        //角色
        $role = Role::find()->where(['disabled'=>0])->all();
        $this->data['role'] = $role;
        $this->data['user'] = User::findOne($user_id);
        $this->data['action'] = 'update&user_id='.$user_id;
        return $this->render('update',$this->data);
    }


    public static function setToken($accid='',$name='')
    {
        $appsecret = \yii::$app->params['appsecret'];
        $url       = 'https://api.netease.im/nimserver/user/create.action';
        $nonce     = mt_rand(1,9999999);
        $time      = time();
        $appkey    = \yii::$app->params['appkey'];

        $CheckSum  = Header::getCheckSum($appsecret,$nonce,$time);
        $res = HttpCurl::request($url,'POST',
            [
                'accid' => $accid,
                'name' => $name,
            ],
            [
//                'Content-Type:application/x-www-form-urlencoded;charset=utf-8',
                'Nonce:'.$nonce,
                'CurTime:'.$time,
                'CheckSum:'.$CheckSum,
                'AppKey:'.$appkey
            ]
        );
        if(!empty($res[0])){
            $obj = json_decode($res[0]);
            if(!empty($obj->info)){
                return ['token'=>json_decode($res[0])->info->token,'accid'=>json_decode($res[0])->info->accid];
            }
            return [];
        }
        return [];
    }

}